//
//  RouterRecordViewController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/6/29.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation
import GTMRefresh
class RouterRecordViewController: UITableViewController {
    
    enum TableDataType {
        case time(User.TripList.TripInfo)
        case date(User.TripList.TripInfo)
        case preorder(Preorder.List.Item)
    }
    
    var data = [TableDataType]()
    var pagex: Int = 1            //默认请求第一页
    
    @IBOutlet weak var InfoView: UIView!
    
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var leftLine : UIView!
    
    @IBOutlet weak var middleButton: UIButton!
    @IBOutlet weak var middleLine: UIView!
    
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var rightLine : UIView!
    
    var orderType = OrderType.preorder   //默认选中预约订单

    override func viewDidLoad() {
        let header = CustomRefreshHeader()
        tableView.gtm_addRefreshHeaderView(refreshHeader: header) { [weak self] in
            self?.requestData(true)
        }
        let footer = CustomRefreshFooter()
        tableView.gtm_addLoadMoreFooterView(loadMoreFooter: footer) { [weak self] in
            self?.requestData(false)
        }
        
        //立即刷新
        tableView.triggerRefreshing()
    }
    
    @IBAction func chooseButton(_ sender: UIButton) {
        leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        middleButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)
        
        leftLine.isHidden = true
        middleLine.isHidden = true
        rightLine.isHidden = true
        
        if sender == leftButton {
            leftLine.isHidden = true
            orderType = .preorder
        } else if sender == middleButton {
            middleLine.isHidden = true
            orderType = .time
        } else if sender == rightButton {
            rightLine.isHidden = true
            orderType = .date
        }
        
        //立即刷新
        tableView.triggerRefreshing()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func requestData(_ isMore: Bool) {
        pagex = isMore ? 1 : pagex + 1
        
        func requestTripList() {
            JZLoading.showLoadingWith(toView: self.view)
            
            User.tripListForme(page: pagex, page_size: 10, kind: orderType, success: { [weak self] data in
                JZLoading.hideLoading()
                
                guard let self = self, let data = data else {
                    return
                }
                
                self.tableView.endRefreshing(isSuccess: true)
                
                let d = data.compactMap { i -> TableDataType in
                    if self.orderType == .time {
                        return TableDataType.time(i)
                    }
                    return TableDataType.date(i)
                }
                
                self.data = isMore ? d : self.data + d
                
                UIView.removeStatusView()
                self.tableView.reloadData()
                if self.data.count == 0 {
                    UIView.showInfoViewWithEmpty(self.view, text: "暂无行程记录", type: .recard)
                    return
                }
            }) { [weak self] error in
                self?.tableView.endRefreshing(isSuccess: true)
                JZLoading.hideLoading()
                self?.showError(error)
            }
        }
        
        func requestPreorderList() {
            JZLoading.showLoadingWith(toView: self.view)
            
            Preorder.list(page: pagex, pageSize: 10, success: { [weak self] data in
                JZLoading.hideLoading()
                
                guard let self = self, let data = data else {
                    return
                }
                
                self.tableView.endRefreshing(isSuccess: true)
                
                let d = data.list.compactMap{ TableDataType.preorder($0) }

                self.data = isMore ? d : self.data + d
                
                UIView.removeStatusView()
                self.tableView.reloadData()
                if self.data.count == 0 {
                    UIView.showInfoViewWithEmpty(self.view, text: "暂无行程记录", type: .recard)
                    return
                }
            }) { [weak self] msg in
                self?.tableView.endRefreshing(isSuccess: true)
                JZLoading.hideLoading()
                self?.showError(msg)
            }
        }
        
        switch orderType {
        case .preorder:
            requestPreorderList()
        case .time, .date:
            requestTripList()
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch data[indexPath.row] {
        case .date(let item):
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            
            if let cell = cell as? MineTripdayCell {
                cell.setItem(item: item)
            }
            
            return cell
        case .time(let item):
            let cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath)
            
            if let cell = cell as? OrderedCell {
                cell.config(item)
            }
            
            return cell
        case .preorder(let item):
            let cell = tableView.dequeueReusableCell(withIdentifier: "preorderCell", for: indexPath)
            
            if let cell = cell as? PreorderCell {
                cell.configure(item: item)
            }
            
            return cell
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return orderType == .time ? 157 : 184
    }
    
    // MARK: - tableView
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        switch data[indexPath.row] {
        case .time(let model):
            //首先判断是否是强制结束的订单
            if model.forceFlag == .forcing {
                performSegue(withIdentifier: "coerceEndOrderSence", sender: model.orderId)
                return
            }
            
            //其次判断是否是欠款订单
            if model.debtFlag == .debted {
                let paramter = ["orderId":model.orderId,
                                "isvisable":Movement.debtOrder] as [String : Any]
                performSegue(withIdentifier: "OrderDetailSence", sender: paramter)
                return
            }
            
            var sceneIndent = ""
            var paramter : Any?
            switch model.status {
            case .reserve, .using://已预订 使用中
                sceneIndent = "preOrderID"
                paramter = model.orderId
            case .cancel:         //已取消
                if model.payStatus == .finish {
                    sceneIndent = "OrderDetailSence"
                    paramter = ["orderId":model.orderId,
                                "isvisable":Movement.cancelOrder]
                } else {//已取消待支付
                    sceneIndent = "orderCancleSence"
                    paramter = model.orderId
                }
            case .confrimReturnCar,.confrimPay://待支付
                sceneIndent = "PayOrderIdentity"
                paramter = model.orderId
            case .finished://已支付
                sceneIndent = "OrderDetailSence"
                paramter = ["orderId":model.orderId,"isvisable":Movement.detailOrder]
            }
            performSegue(withIdentifier: sceneIndent, sender: paramter)
        case .date(let model):
            if model.forceFlag == .forcing {
                performSegue(withIdentifier: "dayrentstrongSence", sender: model.orderId)
                return
            }
            //其次判断是否是欠款订单
            if model.debtFlag == .debted {
                return
            }
            var sceneIndent = ""
            var paramter : Any?
            switch model.status {
            case .reserve:                      //已预订
                sceneIndent = "reserveDayOrderSence"
                paramter = model.orderId
            case .using:                        //使用中(开门 未开门)
                sceneIndent = "preOrderID"
                paramter = model.orderId
            case .confrimReturnCar,.confrimPay: //确认还车 确认支付 （待支付）
                sceneIndent = "DayAwaitPaySence"
                paramter = model.orderId
            case .finished:                    //已支付
                sceneIndent = "dateOrderDetailSegue"
                paramter = ["orderId":model.orderId,"isvisable":Movement.detailOrder]
            default:return
            }
            performSegue(withIdentifier: sceneIndent, sender: paramter)
        case .preorder(let model):
            if model.preorderStatus == 1 {
                performSegue(withIdentifier: "preorderPaySegue", sender: model)
            } else {
                performSegue(withIdentifier: "preorderDetailSegue", sender: model.preorderId)
            }
        }
        
    }
    
    // MARK: - navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        switch segue.identifier {
        case "OrderDetailSence":
            let controller = segue.destination as! OrderDetailViewController
            if let sender = sender as?[String: Any] {
                controller.orderId = sender["orderId"] as? String
                if let type = sender["isvisable"] as? Movement {
                    switch type {
                    case .debtOrder:   controller.page = .debtOrder
                    case .cancelOrder: controller.page = .cancelOrder
                    case .detailOrder: controller.page = .detailOrder
                    }
                }
            }
        case "PayOrderIdentity":
            let controller = segue.destination as! ReturnDetailViewController
            controller.orderId = sender as? String
        case "preOrderID":
            let controller = segue.destination as! PreorderViewController
            controller.orderId = sender as? String
        case "orderCancleSence":
            let controller = segue.destination as! CancelOrderPayViewController
            controller.orderId = sender as? String
        case "dayrentstrongSence":
            let controller = segue.destination as! CoerceEndDayOrderController
            controller.orderId = sender as? String

        case "coerceEndOrderSence":
            let controller = segue.destination as! CoerceEndOrderViewController
            controller.orderId = sender as? String
        case "DayAwaitPaySence":
            let controller = segue.destination as! DayReturnDetailViewController
            controller.orderId = sender as? String
        case "reserveDayOrderSence":
            let controller = segue.destination as! ConfirmPayViewController
            controller.orderId = sender as? String
        case "dateOrderDetailSegue":
            let controller = segue.destination as! OrderDayDetailController
            if let sender = sender as?[String: Any] {
                controller.orderId = sender["orderId"] as? String
//                if let type = sender["isvisable"] as? Movement {
//                    switch type {
//                    case .debtOrder:   controller.page = .debtOrder
//                    case .cancelOrder: controller.page = .cancelOrder
//                    case .detailOrder: controller.page = .detailOrder
//                    }
//                }
            }
        case "preorderDetailSegue":
            if let vc = segue.destination as? PreorderDetailViewController,
                let id = sender as? String {
                vc.preorderId = id
            }
        case "preorderPaySegue":
            if let vc = segue.destination as? PreorderPayViewController,
                let item = sender as? Preorder.List.Item {
                vc.name = item.carTypeName
                vc.address = item.useCarAddress
                vc.useCarTime = TimeInterval(item.useCarTime)
                vc.createData = Preorder.Create(preorderId: item.preorderId,
                                                createdTime: item.createdTime,
                                                balanceFlag: item.balanceFlag,
                                                preorderAmount: item.preorderAmount)
            }
        default:
            break
        }
    }
}
